package com.example.client;

import com.aliyun.com.viapi.FileUtils;
import com.aliyun.tea.TeaException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * 阿里云图像识别分析器
 * 用于垃圾分类识别
 */
public class AliImageAnalyzer {

    /**
     * <b>description</b> :
     * <p>使用凭据初始化账号Client</p>
     * @return Client
     *
     * @throws Exception
     */
    public static com.aliyun.imagerecog20190930.Client createClient() throws Exception {
        // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential);
        // Endpoint 请参考 https://api.aliyun.com/product/imagerecog
        config.endpoint = "imagerecog.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imagerecog20190930.Client(config);
    }

    /**
     * 分析垃圾分类
     * @param filePath 图片文件路径
     * @return 分析结果字符串
     */
    public static String analyzeRubbishImage(String filePath) {
        StringBuilder result = new StringBuilder();
        
        try {
            String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            
            if (accessKeyId == null || accessKeySecret == null) {
                return "错误: 未设置阿里云访问凭据环境变量\n" +
                       "请设置 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET";
            }
            
            result.append("开始分析图片: ").append(filePath).append("\n");
            result.append("正在上传到OSS...\n");
            
            // 上传文件到OSS
            FileUtils fileUtils = FileUtils.getInstance(accessKeyId, accessKeySecret);
            String ossUrl = fileUtils.upload(filePath);
            result.append("OSS上传成功\n\n");
            
            // 创建客户端
            com.aliyun.imagerecog20190930.Client client = AliImageAnalyzer.createClient();
            
            // 构建请求
            com.aliyun.imagerecog20190930.models.ClassifyingRubbishRequest classifyingRubbishRequest = 
                new com.aliyun.imagerecog20190930.models.ClassifyingRubbishRequest()
                    .setImageURL(ossUrl);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            
            result.append("正在调用阿里云图像识别API...\n\n");
            
            // 调用API
            com.aliyun.imagerecog20190930.models.ClassifyingRubbishResponse resp = 
                client.classifyingRubbishWithOptions(classifyingRubbishRequest, runtime);
            
            // 解析并格式化结果
            String jsonResponse = com.aliyun.teautil.Common.toJSONString(resp);
            String formattedResult = parseAndFormatResult(jsonResponse);
            result.append(formattedResult);
            
        } catch (TeaException error) {
            result.append("API调用失败:\n");
            result.append("错误信息: ").append(error.getMessage()).append("\n");
            if (error.getData() != null && error.getData().get("Recommend") != null) {
                result.append("诊断地址: ").append(error.getData().get("Recommend")).append("\n");
            }
        } catch (Exception error) {
            result.append("处理过程中发生错误:\n");
            result.append("错误信息: ").append(error.getMessage()).append("\n");
            result.append("错误类型: ").append(error.getClass().getSimpleName()).append("\n");
        }
        
        return result.toString();
    }
    
    /**
     * 解析并格式化API响应结果
     * @param jsonResponse JSON响应字符串
     * @return 格式化的结果字符串
     */
    private static String parseAndFormatResult(String jsonResponse) {
        try {
            Gson gson = new Gson();
            JsonObject responseObj = gson.fromJson(jsonResponse, JsonObject.class);
            
            // 检查响应状态
            if (responseObj.has("statusCode") && responseObj.get("statusCode").getAsInt() != 200) {
                return "API调用失败，状态码: " + responseObj.get("statusCode").getAsInt();
            }
            
            // 获取body.data.elements数组
            JsonObject body = responseObj.getAsJsonObject("body");
            if (body == null) {
                return "响应格式错误：缺少body字段";
            }
            
            JsonObject data = body.getAsJsonObject("data");
            if (data == null) {
                return "响应格式错误：缺少data字段";
            }
            
            JsonArray elements = data.getAsJsonArray("elements");
            if (elements == null || elements.size() == 0) {
                return "未识别到任何垃圾分类信息";
            }
            
            StringBuilder formattedResult = new StringBuilder();
            formattedResult.append("=== 垃圾分类识别结果 ===\n\n");
            
            // 遍历所有识别结果
            for (int i = 0; i < elements.size(); i++) {
                JsonObject element = elements.get(i).getAsJsonObject();
                
                String category = getStringValue(element, "category", "未知分类");
                double categoryScore = getDoubleValue(element, "categoryScore", 0.0);
                String rubbish = getStringValue(element, "rubbish", "未知物品");
                double rubbishScore = getDoubleValue(element, "rubbishScore", 0.0);
                
                if (i > 0) {
                    formattedResult.append("\n");
                }
                
                formattedResult.append("识别结果 ").append(i + 1).append(":\n");
                formattedResult.append("  物品名称: ").append(rubbish).append("\n");
                formattedResult.append("  垃圾分类: ").append(category).append("\n");
                formattedResult.append("  分类置信度: ").append(String.format("%.2f%%", categoryScore * 100)).append("\n");
                formattedResult.append("  物品置信度: ").append(String.format("%.2f%%", rubbishScore * 100)).append("\n");
                
                // 添加处理建议
                String suggestion = getDisposalSuggestion(category);
                if (!suggestion.isEmpty()) {
                    formattedResult.append("  处理建议: ").append(suggestion).append("\n");
                }
            }
            
            return formattedResult.toString();
            
        } catch (Exception e) {
            return "解析识别结果时发生错误: " + e.getMessage() + "\n\n原始响应:\n" + jsonResponse;
        }
    }
    
    /**
     * 安全获取JSON字符串值
     */
    private static String getStringValue(JsonObject obj, String key, String defaultValue) {
        JsonElement element = obj.get(key);
        return (element != null && !element.isJsonNull()) ? element.getAsString() : defaultValue;
    }
    
    /**
     * 安全获取JSON双精度值
     */
    private static double getDoubleValue(JsonObject obj, String key, double defaultValue) {
        JsonElement element = obj.get(key);
        return (element != null && !element.isJsonNull()) ? element.getAsDouble() : defaultValue;
    }
    
    /**
     * 根据垃圾分类提供处理建议
     */
    private static String getDisposalSuggestion(String category) {
        switch (category) {
            case "湿垃圾":
            case "厨余垃圾":
                return "投放到厨余垃圾桶，可用于堆肥处理";
            case "干垃圾":
            case "其他垃圾":
                return "投放到其他垃圾桶，进行焚烧或填埋处理";
            case "可回收垃圾":
            case "可回收物":
                return "投放到可回收垃圾桶，可进行资源回收利用";
            case "有害垃圾":
                return "投放到有害垃圾桶，需要特殊处理避免污染";
            default:
                return "请根据当地垃圾分类标准进行投放";
        }
    }

    public static void main(String[] args_) throws Exception {
        // 保留原main方法用于测试
        String file = "/Users/Zhuanz/Downloads/apple.jpg";
        String result = analyzeRubbishImage(file);
        System.out.println(result);
    }
}